package com.gcgt.server.trader;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Portfolio {

	private final Map<String, List<Position>> positions = new HashMap<String, List<Position>>();
	
	public List<Position> getPositions(String ticker) {
		List<Position> result = positions.get(ticker);
		
		if (result == null) {
			result = new ArrayList<Position>();
			positions.put(ticker, result);
		}
		
		return result;
	}
	
	public void removePosition(Position position) {
		List<Position> list = positions.get(position.getTicker());
		if (list != null) {
			list.remove(position);
		}
	}
	
	public void addPosition(Position position) {
		List<Position> list = positions.get(position.getTicker());
		if (list == null) {
			list = new ArrayList<Position>();
			positions.put(position.getTicker(), list);
		}
		
		list.add(position);
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Portfolio value " + getValue();
	}
	
	public BigDecimal getValue() {
		BigDecimal result = BigDecimal.ZERO;
		
		for (String ticker : positions.keySet()) {
			for (Position position : positions.get(ticker)) {
				result = result.add(position.getTotalPrice());
			}
		}
		
		return result.setScale(2, BigDecimal.ROUND_HALF_UP);
	}

	public BigDecimal getValue(MarketUpdate update) {
		BigDecimal result = BigDecimal.ZERO;
		
		if (positions.containsKey(update.getTicker())) {
			for (Position position : positions.get(update.getTicker())) {
				result = result.add(update.getOpen().multiply(new BigDecimal(position.getAmount())));
			}
		}
		
		return result.setScale(2, BigDecimal.ROUND_HALF_UP);
	}
}
